package com.googlecode.flealancemarket.tapestry.pages;

import com.googlecode.flealancemarket.core.tapestry.SpringBean;
import com.googlecode.flealancemarket.metamodel.Employer;
import com.googlecode.flealancemarket.metamodel.User;
import com.googlecode.flealancemarket.service.commands.CheckLoginUser;
import com.googlecode.flealancemarket.tapestry.util.Session;
import org.apache.tapestry.annotations.ApplicationState;
import org.apache.tapestry.ioc.annotations.Inject;

public class Login {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @ApplicationState
    private Session session;

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.CheckLoginUser")
    private CheckLoginUser clu;

    @Inject
    @SpringBean("com.googlecode.flealancemarket.metamodel.User")
    private User u;

    Object onSubmitFromUserLogin(){
        u.setUsername(getUsername());
        u.setPassword(getPassword());

        clu.setUser(u);
        User response = clu.execute();
        if(response == null) {
            session.setMessage("There's no such user. Try different username or password.");
            return Login.class;
        } else {
            session.setMessage("Successful login.");
            session.setUserId((Long)response.get_id());
            session.setUsername(response.getUsername());
            boolean emp;
            try {
                Employer e = (Employer)response;
                emp = true;
            } catch (Exception e){
                emp = false;
            }
            session.setUserIsEmployer(emp);
            return Categories.class;
        }
    }
}
